package com.guan.study.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Date: 2023/7/2 15:33
 * @Author: yaobai
 * @Description: 为了通用，该监听器不做数据库相关操作。这是读取excel内容，然后返回出去。
 */
@Slf4j
public class ReadLisitener<T> extends AnalysisEventListener<T> {

    //表头
    Map<Integer, String> tableHeadMap = new HashMap<>();
    //表体
    List<T> list = new ArrayList<>();
    //行号
    List<Integer> rowNoList = new ArrayList<>();

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("表头："+headMap);
        tableHeadMap = headMap;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        ReadRowHolder readRowHolder = analysisContext.readRowHolder();
        Integer rowIndex = readRowHolder.getRowIndex(); //行索引
        log.info("\n读取第" + (rowIndex+1) + "行数据：" + t.toString());
        list.add(t);
        rowNoList.add(rowIndex+1);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("读取excel完毕！读取到的数据 => list = {}",list);
    }
}
